package com.df.ez_game.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.function.Consumer;

@Slf4j
@Data
public class NettyServer {
    EventLoopGroup bossGroup ;
    EventLoopGroup workerGroup ;
    private NettyServerSettings settings;
    public void startUp(Consumer<Channel> successCb,Consumer<Channel> failCb){
        //TODO 不同操作系统的group,option，channel可能不一样，需要根据系统获取
        bossGroup = settings.boosGroup();
        workerGroup = settings.worGroup();

        // netty 服务器
        ServerBootstrap bootstrap = new ServerBootstrap()
                .group(bossGroup, workerGroup);

        settings.settingServerBootStrap(bootstrap);




        try {
            // 真实玩家连接的端口
            ChannelFuture channelFuture = bootstrap.bind(new InetSocketAddress(settings.serverPort())).sync();
//            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            channelFuture.addListener(future -> {
                if(future.isSuccess()){
                    if(successCb!=null){
                        successCb.accept(channelFuture.channel());
                    }
                    //打印banner
                }else {
                    future.cause().printStackTrace();
                    if(failCb!=null){
                        failCb.accept(channelFuture.channel());
                    }
                }
            });

            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        }
    }

    public void shutDown(){
        if(bossGroup!=null){
            bossGroup.shutdownGracefully();
        }
        if(workerGroup!=null){
            workerGroup.shutdownGracefully();
        }
    }
}
